"""
QMT交易客户端 - 模拟实现

【架构说明】
1. 单例模式 - 确保全局唯一实例
2. 线程安全 - 支持异步调用
3. 隔离真实QMT依赖 - 便于测试和开发
4. 专业日志 - 完整操作追踪
"""
import threading
import logging
from typing import Dict, Any, List, Optional
import time
import random

logger = logging.getLogger("QmtClient")

class QmtClient:
    """QMT交易客户端 - 模拟实现"""
    
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        """单例模式实现"""
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
        return cls._instance
    
    def __init__(self):
        """初始化QMT客户端"""
        if hasattr(self, '_initialized') and self._initialized:
            return
            
        # 模拟持仓数据
        self._positions: Dict[str, Dict[str, Any]] = {}
        # 模拟订阅数据
        self._subscriptions: Dict[str, List[str]] = {}
        # 模拟订单数据
        self._orders: Dict[str, Dict[str, Any]] = {}
        
        self._initialized = True
        logger.info("✅ QMT客户端已初始化 (模拟模式)")


    
    def get_account_balance(self) -> float:
        return 1000000.25

    
    def get_stock_positions(self) -> Dict[str, Dict[str, Any]]:
        """
        获取股票持仓 - 模拟实现
        
        返回格式:
        {
            "SH600000": {
                "symbol": "SH600000",
                "volume": 100,
                "price": 10.5,
                "market_value": 1050.0
            }
        }
        """
        # 随机生成一些持仓数据用于演示
        if not self._positions and random.random() > 0.7:
            self._positions = {
                "SH600000": {
                    "symbol": "SH600000",
                    "volume": 100,
                    "price": round(10.0 + random.uniform(-1, 1), 2),
                    "market_value": 1050.0
                },
                "SZ000001": {
                    "symbol": "SZ000001",
                    "volume": 200,
                    "price": round(15.0 + random.uniform(-1, 1), 2),
                    "market_value": 3000.0
                }
            }
            logger.info(f"🎲 生成模拟持仓数据: {list(self._positions.keys())}")
        
        return self._positions.copy()
    
    def order_stock(self, stock_code: str, volume: int, price: float = 0.0, 
                   order_type: str = "market") -> str:
        """
        下单函数 - 模拟实现
        
        参数:
        - stock_code: 股票代码，如 "SH600000"
        - volume: 交易数量，正数为买入，负数为卖出
        - price: 价格，0表示市价单
        - order_type: 订单类型，"market" 或 "limit"
        
        返回:
        - 订单ID
        """
        order_id = f"order_{int(time.time())}_{random.randint(1000, 9999)}"
        
        # 模拟订单执行
        order = {
            "order_id": order_id,
            "stock_code": stock_code,
            "volume": volume,
            "price": price if price > 0 else random.uniform(9.5, 11.5),
            "order_type": order_type,
            "status": "filled",
            "filled_volume": abs(volume),
            "filled_price": price if price > 0 else random.uniform(9.5, 11.5),
            "timestamp": time.time()
        }
        
        self._orders[order_id] = order
        
        # 更新持仓
        if volume != 0:
            current_pos = self._positions.get(stock_code, {
                "symbol": stock_code,
                "volume": 0,
                "price": 0.0,
                "market_value": 0.0
            })
            
            new_volume = current_pos["volume"] + volume
            new_price = order["filled_price"]
            
            if new_volume > 0:
                # 买入或部分卖出后仍有持仓
                self._positions[stock_code] = {
                    "symbol": stock_code,
                    "volume": new_volume,
                    "price": new_price,
                    "market_value": new_volume * new_price
                }
            elif new_volume == 0:
                # 完全平仓
                self._positions.pop(stock_code, None)
            else:
                # 卖空 (这里简化处理)
                self._positions[stock_code] = {
                    "symbol": stock_code,
                    "volume": new_volume,
                    "price": new_price,
                    "market_value": new_volume * new_price
                }
        
        action = "买入" if volume > 0 else "卖出"
        logger.info(f"💰 {action} {stock_code} {abs(volume)}股 @ {order['filled_price']:.2f} (订单ID: {order_id})")
        
        return order_id
    
    def subscribe(self, stock_code: str):
        """订阅行情 - 模拟实现"""
        logger.info(f"🔔 模拟订阅行情: {stock_code}")
        # 实际项目中这里会调用QMT的真实订阅函数
        return True
    
    def get_current_data(self, stock_code: str) -> Dict[str, Any]:
        """获取当前行情数据 - 模拟实现"""
        # 模拟随机价格波动
        base_price = 10.0
        if stock_code in self._positions:
            base_price = self._positions[stock_code]["price"]
        
        current_price = round(base_price * (1 + random.uniform(-0.02, 0.02)), 2)
        return {
            "stock_code": stock_code,
            "last_price": current_price,
            "open": round(current_price * (1 + random.uniform(-0.01, 0.01)), 2),
            "high": round(current_price * (1 + random.uniform(0.01, 0.03)), 2),
            "low": round(current_price * (1 - random.uniform(0.01, 0.03)), 2),
            "volume": random.randint(1000000, 10000000),
            "timestamp": time.time()
        }
    
    def cancel_order(self, order_id: str) -> bool:
        """取消订单 - 模拟实现"""
        if order_id in self._orders:
            self._orders[order_id]["status"] = "cancelled"
            logger.info(f"❌ 订单已取消: {order_id}")
            return True
        return False
    
    def get_orders(self) -> List[Dict[str, Any]]:
        """获取订单列表 - 模拟实现"""
        return list(self._orders.values())

# 导出单例实例
qmt_client = QmtClient()